﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aribaccio;
using Aribaccio.Datum;
using BDPAutodetect.Device;
using BDPAutodetect.Hardware;

namespace BDPAutodetect.Mgrcore
{
    /// <summary>
    /// 设备存储连接配置管理
    /// </summary>
    public class StorageDeviceManager : BaseManager
    {
        /// <summary>
        /// 存储文件实例
        /// </summary>
        protected StorageXmlFile StorageFile { get; set; }
        /// <summary>
        /// 设备集参数管理
        /// </summary>
        protected DeviceParaManager DeviceParaMgr { get; set; }
        /// <summary>
        /// 配置设备相对路径名称
        /// </summary>
        protected string ConfigDeviceName => GlobalDefine.ConfigDevicePathName;
        /// <summary>
        /// 配置设备全路径名称
        /// </summary>
        public string ConfigDevicePathName => PathHelper.GetPathFullFileName(this.ConfigDeviceName);

        /// <summary>
        /// 构造函数[注入]
        /// </summary>
        public StorageDeviceManager(DeviceParaManager argDeviceParaManager)
            : base("设备存储连接配置管理中心")
        {
            this.StorageFile = new StorageXmlFile(this.Name);
            this.DeviceParaMgr = argDeviceParaManager;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public override async Task Initialize()
        {
            //获取存储通道数据对象
            var TaskResult = this.ReadConfig<ReturnData>();
            await TaskResult.ConfigureAwait(false);
            //异步等待返回结果
            if (TaskResult.Result.ResultState && TaskResult.Result.Data != null)
            {
                //存储通道和配置表
                this.DeviceParaMgr.Initialize(TaskResult.Result.Data);
                this.DeviceParaMgr.OpenDeviceAll();
            }
        }

        /// <summary>
        /// 写入XML文件配置信息
        /// </summary>
        /// <param name="argXMLData">XML存储对象</param>
        /// <returns></returns>
        public Task<Result> WriteConfig<T>(T argXMLData) where T : class, new()
        {
            //等待Task返回，此时不会阻碍主线程的执行
            return Task.Run(() =>
            {
                return this.StorageFile.XMLWriteData(argXMLData, this.ConfigDevicePathName);
            });
        }

        /// <summary>
        /// 读取XML文件配置信息
        /// </summary>
        /// <returns></returns>
        public Task<ResultModel<T>> ReadConfig<T>() where T : class, new()
        {
            //等待Task返回，此时不会阻碍主线程的执行
            return Task.Run(() =>
            {
                return this.StorageFile.XMLReadStreamData<T>(this.ConfigDevicePathName);
            });
        }
    }
}
